<html>
<head>
<!-- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" /> -->
  <script type="text/javascript" src="js/jquery-combined.js"></script>
  <script type="text/javascript" src="js/common.js"></script>
  <script type="text/javascript" src="js/sabconnect.js"></script>

<script>
var gTimer;
var gSabInfo;

var active_daemon;
var last_queueinfo;

try{
  active_daemon = getPref('daemons')[0];
}catch (e){
  active_daemon = {label:'localhost',url:'localhost:8080/sabnzbd',apikey:''};
}


var img_g = chrome.extension.getURL('images/sab2_16_green.png');

//console.log('bg load');

$(document).ready(function() {
    setDefaults();
    startTimer();
    //console.log('bg ready');
});


function startTimer() {
    if(gTimer) {
        clearInterval(gTimer);
    } else {
        fetchInfo();
    }
    //getPref('refresh_rate')
    gTimer = setInterval(fetchInfo, 3*1000);
}

function fileSizes(value, decimals){
    // Set the default decimals to 2
    if(decimals == undefined)
        decimals = 2;

    kb = value / 1024
    mb = value / 1048576
    gb = value / 1073741824
    if (gb >= 1){
        return gb.toFixed(decimals)+"GB"
    } else if (mb >= 1) {
        return mb.toFixed(decimals)+"MB"
    } else {
        return kb.toFixed(decimals)+"KB"
    }
}       //file size formatter - takes an input in bytes


function setDefaults() {

    // new user
    if((getPref('sab_url') === undefined) && getPref('daemons') === undefined){

    }else
    // upgrading user
    if (getPref('sab_url') === undefined){
        console.log('writing default settings');
        
        setPref('refresh_rate', 15);
        setPref('sab_url', 'http://localhost:8080/sabnzbd/');
        setPref('api_key', '');
        setPref('speedlog', []);

        setPref('enable_messenger', 1);
        setPref('show_graph', 0);
        setPref('enable_newzbin', 1);
        setPref('enable_tvnzb', 1);
        setPref('enable_nzbmatrix', 1);
    }

    if(getPref('refresh_rate') === undefined) setPref('refresh_rate', 15);

    if(getPref('daemons') === undefined ) {
        if(! (getPref('sab_url') === undefined)){
            daemons = [{label:'my sabnzbd+',url:getPref('sab_url'),apikey:getPref('api_key')}];
        }else{
            daemons = [{label:'localhost',url:'http://localhost:8080/sabnzbd/',apikey:''}];
        }
        setPref('daemons', daemons);
        active_daemon = daemons[0];
    }else{
        var daemons = getPref('daemons');

        if (daemons.length > 0){
            active_daemon = daemons[0];
        }
    }

}
/*
chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
    else
      sendResponse({}); // snub them.
  });
*/

// Listen for notifications from the content script.
chrome.extension.onConnect.addListener(function(port, name) {
    port.onMessage.addListener(function(msg) {
      //console.log("background.onMessage: ");
      //console.log(msg);
        if(msg.get && msg.key) {
          var key = msg.key;

          switch(key){
            case 'addurl':
              console.log(msg.get);
              SABConnect.addurl(msg.get);
              break;
          
            case 'active_daemon':
              sendConfigResponse(key, active_daemon);
              break;
            default: 
              sendConfigResponse(key, getPref(key));
              break;
          }
            
        }
    });
});


function sendConfigResponse(k, v) {
  console.log('send=>{'+k+':'+v+'}');
  chrome.tabs.getSelected(null, function(tab) {
    var port = chrome.tabs.connect(tab.id, {name: "notifyChannelOut"});
    port.postMessage({key: k, value: v});
  });
}


/**
 * quickUpdate
 *     If set to true, will not update the graph ect, currently used when a queue item has been moved/deleted in order to refresh the queue list
 */
function fetchInfo() {
    //console.log('fetchInfo');
    var data = {};
    data.daemon = active_daemon;
    data.opts   = {};
    data.opts.limit = '5';
    data.success = function(data){
        if (last_queueinfo == undefined){
            //console.log(data);
        }
        last_queueinfo = data.queue;
        update_badge();
    };

    SABConnect.queue_json(data);
}


function update_badge(){
    //console.log('updateBadge');

    var queue = last_queueinfo;
    //console.log(data);
    
    // Update the badge
    var badge = {};
    // Set the text on the object to be the number of items in the queue
    // +'' = converts the int to a string.
    badge.text = queue.noofslots+'';
    chrome.browserAction.setBadgeText(badge);

    // Update the background based on if we are downloading
    if(queue.kbpersec && queue.kbpersec > 1) {
        badgeColor = {color: new Array(0, 213, 7, 100)}
        chrome.browserAction.setBadgeBackgroundColor(badgeColor)
    } else {
      // Not downloading
        badgeColor = {color: new Array(255, 0, 0, 100)}
        chrome.browserAction.setBadgeBackgroundColor(badgeColor)
    }
}



</script>
</head>
<body></body>
</html>